package com.gitee.empty_null.context;

import com.gitee.empty_null.properties.SparkChatProperty;
import org.jetbrains.annotations.NotNull;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author xuhainan
 * @date 2023/11/21 13:32
 * @region hefei
 */
public class SparkChatContextHolder {

    private final static Map<String, SparkChatProperty> CHAT_PROPERTY_MAP = new LinkedHashMap<>(4);
    private final static ThreadLocal<SparkChatProperty> currentProperty = new ThreadLocal<>();


    public static void add(SparkChatProperty property) {
        CHAT_PROPERTY_MAP.put(property.getAppid(), property);
    }

    public static void addAll(@NotNull List<SparkChatProperty> propertyList) {
        Map<String, SparkChatProperty> propertyMap = propertyList.stream()
                .collect(Collectors.toMap(SparkChatProperty::getAppid, Function.identity(), (o1, o2) -> o1, LinkedHashMap::new));
        CHAT_PROPERTY_MAP.putAll(propertyMap);
    }

    public static void remove(@NotNull SparkChatProperty property) {
        CHAT_PROPERTY_MAP.remove(property.getAppid());
        currentProperty.remove();
    }

    public static SparkChatProperty get() {
        SparkChatProperty chatProperty = currentProperty.get();
        if (Objects.isNull(chatProperty)) {
            chatProperty = CHAT_PROPERTY_MAP.values()
                    .stream()
                    .findFirst()
                    .orElseThrow(() -> new IllegalStateException("暂无可用配置信息"));
            currentProperty.set(chatProperty);
        }
        return chatProperty;
    }

    public static void match(String appid) {
        SparkChatProperty matchProperty = CHAT_PROPERTY_MAP.get(appid);
        if (Objects.nonNull(matchProperty)) {
            currentProperty.set(matchProperty);
        }
        throw new IllegalArgumentException("当前appId[" + appid + "]不存在");
    }

}
